package com.yiqixuejava.reconciliation.service.impl;

import com.yiqixuejava.reconciliation.dto.RDetail;
import com.yiqixuejava.reconciliation.entity.SourceEntity;
import com.yiqixuejava.reconciliation.exception.ServiceException;
import com.yiqixuejava.reconciliation.service.ReconService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 类的描述：
 *
 * @author: huxp
 * @createDate: 2019/11/11 17:14
 * @version: v1.0
 */
@Service("WebChatReconService")
@Scope("prototype")
public class WebChatReconService implements ReconService {
    private Logger log = LoggerFactory.getLogger(getClass());
    private static final String WXPAY_FILE_CODE = "UTF-8";
    private static final String REFUND = "REFUND";
    private int currentCount = 0;
    private int index = 1;
    //记录总数
    private int totolCount;
    //每条记录字段数量
    private int fieldCount;
    private String[] fileContent;

    @Override
    public void prepare(SourceEntity sourceEntity) throws ServiceException {
        currentCount = 0;
        BufferedReader reader = null;
        try {
            File file = new File(sourceEntity.getUri());
            //解决中文乱码
            InputStreamReader isr = null;
            isr = new InputStreamReader(new FileInputStream(file), WXPAY_FILE_CODE);
            reader = new BufferedReader(isr);
            StringBuffer content = new StringBuffer();
            int ch;
            while ((ch = reader.read()) != -1) {
                content.append((char) ch);
            }
            String csvContent = content.toString();
            //正常的交易报文
            String listStr = "";
            if (csvContent.contains("总交易单数")) {
                listStr = csvContent.substring(0, csvContent.indexOf("总交易单数"));
                // ,转化成空格
                csvContent = csvContent.replaceAll(",", " ");
                // 数据分组
                fileContent = csvContent.split("`");
                String[] t = fileContent[0].split(" ");// 分组标题
                totolCount = (fileContent.length - 1) / t.length; // 计算循环次数
                fieldCount = t.length;
                index = 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<RDetail> getNextData(int maxSize) {
        List<RDetail> list = null;
        while (currentCount < totolCount) {
            RDetail wxRecord = new RDetail();
            /*********************** 我添加的开始 ***********************/
            //如果是最后列且是最后一行数据时，去除数据里的汉字
            String reg = "[\u4e00-\u9fa5]";//汉字的正则表达式
            Pattern pat = Pattern.compile(reg);
            //存入实体类
            wxRecord.setTradeDateTime(pat.matcher(fileContent[index++]).replaceAll("").trim());//交易时间
            index++;//公众账号 ID
            index++;//商户号
            index++;//特约商户号
            index++;//设备号
            index++;//银联订单号

            String orderNo = pat.matcher(fileContent[index++]).replaceAll("").trim();//商户订单号

            index++;//用户标识
            index++;//交易类型

            String orderStatus = pat.matcher(fileContent[index++]).replaceAll("").trim();//交易状态

            index++;//截取付款银行
            index++;//货币种类
            index++;//应结订单金额
            index++;//代金券金额
            index++;//银联退款单号
            String refundOrderNo = pat.matcher(fileContent[index++]).replaceAll("").trim();//商户退款单号
            String refundAmount = pat.matcher(fileContent[index++]).replaceAll("").trim();//退款金额
            index++;//充值券退款金额
            index++;//退款类型
            index++;//退款状态
            index++;//商品名称
            index++;//商户数据包
            index++;//手续费
            index++;//费率
            if (REFUND.equals(orderStatus)) {
                index++;//交易金额
                wxRecord.setOrderNo(refundOrderNo);//商户退款订单号设置为商户订单号
                //退款订单单位为元转换成分
                wxRecord.setTradeAmount(new BigDecimal(refundAmount).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).toPlainString());//退款金额设置到-》订单金额，方便后期对账

            } else {
                wxRecord.setOrderNo(orderNo);
                wxRecord.setTradeAmount(new BigDecimal(pat.matcher(fileContent[index++]).replaceAll("").trim()).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).toPlainString());//订单金额
            }
            index++;//申请退款金额
            index++;//费率备注

            if (null == list) {
                list = new ArrayList<>();
            }
            list.add(wxRecord);
            currentCount++;
            if (list.size() >= maxSize) {
                break;
            }
        }
        return list;
    }

    @Override
    public void destroy() {

    }
}
